#!/bin/sh
#####################################################
# 使用说明：                                          #
# 部署：sh deploy.sh start                           #
# 重启：sh deploy.sh restart                         #
# 停止：sh deploy.sh stop                            #
#####################################################

#变量
SERVER_NAME="ratel-web"
JAR_NAME="${SERVER_NAME}.jar"
PROFILES_ACTIVE="prod"
SERVER_HOME="/www/server/${SERVER_NAME}"
LOGGER_HOME="${SERVER_HOME}/logs"
GC_LOGGER_HOME="${LOGGER_HOME}/gc"

#创建目录
echo "创建日志目录 LOGGER_HOME=$LOGGER_HOME"
if [ ! -d $GC_LOGGER_HOME ]; then
  mkdir -p $GC_LOGGER_HOME
fi

# jvm 参数
[ -z "$JAVA_OPTS" ] && JAVA_OPTS=" -Xms2048M -Xmx2048M -Xmn1024M -Xss256k "

SERVER_OPTS=" ${JAVA_OPTS} \
-XX:MetaspaceSize=64m \
-XX:MaxMetaspaceSize=256m \
-XX:MaxDirectMemorySize=256m \
-XX:+UseCompressedClassPointers \
-XX:CompressedClassSpaceSize=64m \
-XX:+UseConcMarkSweepGC \
-XX:ParallelCMSThreads=2 \
-XX:+CMSClassUnloadingEnabled \
-XX:+UseCMSCompactAtFullCollection \
-XX:CMSInitiatingOccupancyFraction=80 \
-verbose:gc \
-XX:+PrintGCDateStamps \
-XX:+PrintGCTimeStamps \
-XX:+PrintReferenceGC \
-XX:+PrintGCDetails \
-XX:+PrintTenuringDistribution \
-XX:SurvivorRatio \
-XX:+PrintCommandLineFlags \
-XX:+ExplicitGCInvokesConcurrent \
-XX:+UseGCLogFileRotation \
-XX:+UseStringDeduplication \
-Djava.security.egd=file:/dev/./urandom \
-XX:GCLogFileSize=50M \
-XX:NumberOfGCLogFiles=10 \
-Xloggc:${GC_LOGGER_HOME}/gc-%t.log \
-XX:-OmitStackTraceInFastThrow \
-XX:+HeapDumpOnOutOfMemoryError \
-XX:HeapDumpPath=${LOGGER_HOME}/java_heapdump.hprof"

# 启动服务
start() {
    # 启动服务
    eval exec "java -server $SERVER_OPTS \
        -jar $SERVER_HOME/$JAR_NAME \
        --spring.profiles.active=$PROFILES_ACTIVE \
        -DLOGGING_PATH=$LOGGER_HOME \
        -Duser.timezone=Asia/Shanghai \
        -Dfile.encoding=UTF-8 \
        -Djava.security.egd=file:/dev/./urandom \
        >> $LOGGER_HOME/nohup.log 2>&1 &"
    # 打印结果
    if [ $? -eq 0 ]; then
        sleep 1
        echo "运行服务：“$SERVER_NAME”"
        echo "完成部署：重启成功！！！"
    else
        echo "服务：“$SERVER_NAME” 启动失败！！！"
        exit 2
    fi
}

# kill 老服务
stop() {
	PIDS=`ps -ef | egrep '$JAR_NAME' | grep -v grep | grep -v tail | awk '{print $2}'`
	PID_COUNT=${#PIDS[@]}
	if [ $PID_COUNT -lt 1 ] ; then
		echo "停止服务：跳过，不存在名称为“$JAR_NAME”的服务"
	elif [ $PID_COUNT -gt 1 ]; then
		# 多个同名服务，不做停止处理
		echo "停止服务：失败，“$JAR_NAME” 服务存在多个，请管理员确定停止方案"
		return 1
	else
		# 停止服务
		ps -ef | grep $JAR_NAME | grep -v grep | awk '{print $2}' | xargs kill -9
		echo "停止服务：“$JAR_NAME”"
	fi
}

# 重启
restart() {
	if [ ! -f "${SERVER_HOME}/${JAR_NAME}" ]; then
		echo "jar 文件：“${SERVER_HOME}/${JAR_NAME}” 不存在启动失败！！！"
		exit 4
	fi
	# 停止老服务
	stop
	# 启动服务
	start
}

case "$1" in
	start)
		start
		;;
	restart)
		restart
		;;
	stop)
		stop
		;;
   *)
    echo -e $"=== Run $0 Use arg:  { start | restart | stop } ==="
esac
exit $?
